#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  showenv.py
#       Author @  Huoty
#  Create date @  2016-01-30 17:56:23
#  Description @  Show client request info
# *************************************************************

from __future__ import print_function

from wsgiref.simple_server import make_server


PORT = 12018
HOST = "127.0.0.1"


def create_template(filename):
    tpl = ""
    with open(filename, "r") as file_obj:
        for line in file_obj.readlines():
            if line != "\n":
                tpl = "".join([tpl, line.strip()])
    return tpl


def application(environ, start_response):
    # Response body
    env_items = [ "<tr><td>%s</td><td>%s</td></tr>" % (key, val) \
            for key, val in sorted(environ.items()) ]
    response_body = create_template("getenv.tpl") % "".join(env_items)

    # Length of response body
    content_len = len(response_body)

    # Status code and response headers
    status = "200 OK"
    response_headers = [("Content-Type", "text/html"), ("Content-Length", str(content_len))]

    # Use callback function to send back status code
    # and response headers
    start_response(status, response_headers)

    # return response body through return statement
    return response_body


if __name__ == "__main__":
    # Create web server
    httpd = make_server(HOST, PORT, application)

    # Print prompting message
    print("Starting http server at http://%s:%s/" % (HOST, str(PORT)))
    print("Quit the server with CONTROL-C.")

    # Listen http request
    httpd.serve_forever()
